package com.ajun;

import cn.hutool.core.date.DateUtil;
import com.ajun.notice.RobotNotice;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;

/**
 * @author LiJun
 * @date 2021-07-29
 */
@Slf4j
@Component
public class SendTask {

    @Resource
    RobotNotice robotNotice;

    @Scheduled(cron = "*/1 * * * * ?")
    private void executeGoHomeTask() {
        LocalTime timeOfGoHome = LocalTime.of(18, 0, 0);
        LocalTime timeOfNow = LocalTime.now();
        long hours = timeOfNow.until(timeOfGoHome, ChronoUnit.HOURS);
        timeOfNow = timeOfNow.plusHours(hours);
        long minutes = timeOfNow.until(timeOfGoHome, ChronoUnit.MINUTES);
        timeOfNow = timeOfNow.plusMinutes(minutes);
        long seconds = timeOfNow.until(timeOfGoHome, ChronoUnit.SECONDS);
        String msgFormat = "️⏰⏰⏰ %d小时%d分%d秒后到下班时间!!!";
        if (hours <= 0 && minutes <= 0) {
            msgFormat = "⏰⏰⏰ %d秒后到下班时间!!!";
            executeTextTask(String.format(msgFormat, seconds));
            return;
        }
        if (hours <= 0) {
            msgFormat = "⏰⏰⏰ %d分%d秒后到下班时间!!!";
            executeTextTask(String.format(msgFormat, minutes, seconds));
            return;
        }
        executeTextTask(String.format(msgFormat, hours, minutes, seconds));
    }

    private void executeTextTask(String text) {
        try {
            log.info("执行任务开始...date:{}, msg:{}", DateUtil.now(), text);
            robotNotice.sendMessage(text);
            log.info("执行任务完成...");
        } catch (Exception ex) {
            log.error(ex.getMessage());
        }
    }
}
